package com.pdstudio.app;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;

import cn.jpush.android.api.JPushInterface;

import com.baidu.location.LocationClient;
import com.baidu.location.LocationClientOption;
import com.baidu.mapapi.SDKInitializer;
import com.nostra13.universalimageloader.cache.disc.impl.UnlimitedDiscCache;
import com.nostra13.universalimageloader.cache.disc.naming.Md5FileNameGenerator;
import com.nostra13.universalimageloader.cache.memory.impl.UsingFreqLimitedMemoryCache;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.ImageLoaderConfiguration;
import com.nostra13.universalimageloader.core.assist.QueueProcessingType;
import com.nostra13.universalimageloader.core.download.BaseImageDownloader;
import com.nostra13.universalimageloader.utils.StorageUtils;
import com.pdstudio.bean.City;
import com.pdstudio.bean.Pm2d5;
import com.pdstudio.bean.SimpleCity;
import com.pdstudio.bean.SimpleWeatherinfo;
import com.pdstudio.bean.Weatherinfo;
import com.pdstudio.db.CityDB;
import com.pdstudio.http.StationHttpMethod;
import com.pdstudio.http.WeatherHttpMethod;
import com.pdstudio.util.NetUtil;
import com.pdstudio.util.SharePreferenceUtil;
import com.pdstudio.util.T;
import com.pdstudio.weather.R;

public class Application extends android.app.Application {
	public static ArrayList<EventHandler> mListeners = new ArrayList<EventHandler>();
	private static String NET_CHANGE_ACTION = "android.net.conn.CONNECTIVITY_CHANGE";
	private static final int CITY_LIST_SCUESS = 0;
	private static final int ALL_CITYS = 1;
	private static final int AUDIO_PATH = 2;
	private static final String FORMAT = "^[a-z,A-Z].*$";
	private static Application mApplication;
	private CityDB mCityDB;
	private Map<String, Integer> mWeatherIcon;// 天气图标
	private Map<String, Integer> mWarningIcon;// 预警图标
	private Map<String, Integer> mWidgetWeatherIcon;// 插件天气图标
	private Map<String, Integer> mWeatherBg;
	private List<City> mCityList;
	// 首字母集
	private List<String> mSections;
	// 根据首字母存放数据
	private Map<String, List<City>> mMap;
	// 首字母位置集
	private List<Integer> mPositions;
	// 首字母对应的位置
	private Map<String, Integer> mIndexer;
	private boolean isCityListComplite;

	private LocationClient mLocationClient = null;
	private SharePreferenceUtil mSpUtil;
	private Weatherinfo mCurWeatherinfo;
	private SimpleWeatherinfo mCurSimpleWeatherinfo;
	private Pm2d5 mCurPm2d5;
	private SimpleCity mCurSimpleCity;// 当前城市
	private Map<String, SimpleCity> allCitys;// 所有城市，code对应simplecity
	private String curAudioPath;// 当前城市对应的播放地址
	public static int mNetWorkState;

	private Handler mHandler = new Handler() {
		@Override
		public void handleMessage(android.os.Message msg) {
			switch (msg.what) {
			case CITY_LIST_SCUESS:
				isCityListComplite = true;
				if (mListeners.size() > 0)// 通知接口完成加载
					for (EventHandler handler : mListeners) {
						handler.onCityComplite();
					}
				break;
			case ALL_CITYS: {
				try {
					if (msg != null && msg.obj != null) {
						allCitys = (Map<String, SimpleCity>) msg.obj;
					}
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
				break;
			case AUDIO_PATH: {
				if (msg != null && msg.obj != null) {
					try {
						curAudioPath = (String) msg.obj;
					} catch (Exception e) {
						e.printStackTrace();
					}
				}
			}
				break;
			default:
				break;
			}
		}
	};

	public static synchronized Application getInstance() {
		return mApplication;
	}

	@Override
	public void onCreate() {
		// TODO Auto-generated method stub
		super.onCreate();



		initData();
	}

	/*
	 * 去掉了一个loca的so文件，缺的文件可以跟以前的备份对比，因为没有那三个方法，所以注释掉
	 */
	private LocationClientOption getLocationClientOption() {
		LocationClientOption option = new LocationClientOption();
		option.setOpenGps(true);
		option.setAddrType("all");
		option.setServiceName(this.getPackageName());
		option.setScanSpan(0);
		option.disableCache(true);
		return option;
	}

	private void initData() {

		// 在使用 SDK 各组间之前初始化 context 信息，传入 ApplicationContext
		SDKInitializer.initialize(this);

		// 极光推送
		// JPushInterface.setDebugMode(true); // 设置开启日志,发布时请关闭日志
		JPushInterface.init(this); // 初始化 JPush

		// 初始化图片加载库
		initalImageLoader();

		mApplication = this;
		mNetWorkState = NetUtil.getNetworkState(this);

		mSpUtil = new SharePreferenceUtil(this,
				SharePreferenceUtil.CITY_SHAREPRE_FILE);
		initCityList();
		mLocationClient = new LocationClient(this, getLocationClientOption());
		initWeatherIconMap();
		initWidgetWeather();
		initWarningIconMap();
		initApplicationBackground();
		initAllCitys();
		initalCurSimpleCity();
		IntentFilter filter = new IntentFilter(NET_CHANGE_ACTION);
		registerReceiver(netChangeReceiver, filter);
	}

	/*
	 * 图片加载库初始化
	 */
	private void initalImageLoader() {
		try {
			File cacheDir = StorageUtils.getOwnCacheDirectory(
					getApplicationContext(), "yueyangweather/Cache/Image");
			ImageLoaderConfiguration config = new ImageLoaderConfiguration.Builder(
					getApplicationContext())
					.memoryCacheExtraOptions(480, 800)
					// max width, max height，即保存的每个缓存文件的最大长宽
					// .discCacheExtraOptions(480, 800, CompressFormat.JPEG, 75,
					// null) // Can slow ImageLoader, use it carefully (Better
					// don't
					// use it)/设置缓存的详细信息，最好不要设置这个
					.threadPoolSize(3)
					// 线程池内加载的数量
					.threadPriority(Thread.NORM_PRIORITY - 2)
					.denyCacheImageMultipleSizesInMemory()
					.memoryCache(
							new UsingFreqLimitedMemoryCache(2 * 1024 * 1024))
					// You can pass your own memory cache
					// implementation/你可以通过自己的内存缓存实现
					.memoryCacheSize(2 * 1024 * 1024)
					.discCacheSize(50 * 1024 * 1024)
					.discCacheFileNameGenerator(new Md5FileNameGenerator())
					// 将保存的时候的URI名称用MD5 加密
					.tasksProcessingOrder(QueueProcessingType.LIFO)
					.discCacheFileCount(100) // 缓存的文件数量
					.discCache(new UnlimitedDiscCache(cacheDir))// 自定义缓存路径
					.defaultDisplayImageOptions(
							DisplayImageOptions.createSimple())
					.imageDownloader(
							new BaseImageDownloader(getApplicationContext(),
									5 * 1000, 30 * 1000)) // connectTimeout (5
															// s),
															// readTimeout (30
															// s)超时时间
					.writeDebugLogs() // Remove for release app
					.build();// 开始构建
			// Initialize ImageLoader with configuration.
			ImageLoader.getInstance().init(config);// 全局初始化此配置
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public synchronized CityDB getCityDB() {
		if (mCityDB == null)
			mCityDB = openCityDB();
		return mCityDB;
	}

	public synchronized SharePreferenceUtil getSharePreferenceUtil() {
		if (mSpUtil == null)
			mSpUtil = new SharePreferenceUtil(this,
					SharePreferenceUtil.CITY_SHAREPRE_FILE);
		return mSpUtil;
	}

	public synchronized LocationClient getLocationClient() {
		if (mLocationClient == null)
			mLocationClient = new LocationClient(this,
					getLocationClientOption());
		return mLocationClient;
	}

	private CityDB openCityDB() {
		String path = "/data"
				+ Environment.getDataDirectory().getAbsolutePath()
				+ File.separator + "com.pdstudio.weather" + File.separator
				+ CityDB.CITY_DB_NAME;
		File db = new File(path);
		if (!db.exists()) {
			// L.i("db is not exists");
			try {
				InputStream is = getAssets().open("city.db");
				FileOutputStream fos = new FileOutputStream(db);
				int len = -1;
				byte[] buffer = new byte[1024];
				while ((len = is.read(buffer)) != -1) {
					fos.write(buffer, 0, len);
					fos.flush();
				}
				fos.close();
				is.close();
			} catch (IOException e) {
				e.printStackTrace();
				T.showLong(mApplication, e.getMessage());
				System.exit(0);
			}
		}
		return new CityDB(this, path);
	}

	public List<City> getCityList() {
		return mCityList;
	}

	public List<String> getSections() {
		return mSections;
	}

	public Map<String, List<City>> getMap() {
		return mMap;
	}

	public List<Integer> getPositions() {
		return mPositions;
	}

	public Map<String, Integer> getIndexer() {
		return mIndexer;
	}

	public boolean isCityListComplite() {
		return isCityListComplite;
	}

	public Map<String, Integer> getWeatherIconMap() {
		return mWeatherIcon;
	}

	public Map<String, Integer> getWarningIconMap() {
		return mWarningIcon;
	}

	public int getWarningIcon(String warning) {
		int warningIcon = R.drawable.nowarning;
		if (mWarningIcon.containsKey(warning)) {
			warningIcon = mWarningIcon.get(warning);
		}
		return warningIcon;
	}

	public int getWeatherIcon(String climate) {
		int weatherRes = R.drawable.biz_plugin_weather_qing;
		if (TextUtils.isEmpty(climate))
			return weatherRes;
		String[] strs = { "晴", "晴" };
		if (climate.contains("转")) {// 天气带转字，取前面那部分
			strs = climate.split("转");
			climate = strs[0];
			if (climate.contains("到")) {// 如果转字前面那部分带到字，则取它的后部分
				strs = climate.split("到");
				climate = strs[1];
			}
		}
		if (mWeatherIcon.containsKey(climate)) {
			weatherRes = mWeatherIcon.get(climate);
		}
		return weatherRes;
	}

	public int getWidgetWeatherIcon(String climate) {
		int weatherRes = R.drawable.na;
		if (TextUtils.isEmpty(climate))
			return weatherRes;
		String[] strs = { "晴", "晴" };
		if (climate.contains("转")) {// 天气带转字，取前面那部分
			strs = climate.split("转");
			climate = strs[0];
			if (climate.contains("到")) {// 如果转字前面那部分带到字，则取它的后部分
				strs = climate.split("到");
				climate = strs[1];
			}
		}
		if (mWidgetWeatherIcon.containsKey(climate)) {
			weatherRes = mWidgetWeatherIcon.get(climate);
		}
		return weatherRes;
	}

	public int getApplicationBackground(String climate) {
		int bgRes = R.drawable.sun;
		if (TextUtils.isEmpty(climate))
			return bgRes;
		String[] strs = { "晴", "晴" };
		if (climate.contains("转")) {// 天气带转字，取前面那部分
			strs = climate.split("转");
			climate = strs[0];
			if (climate.contains("到")) {// 如果转字前面那部分带到字，则取它的后部分
				strs = climate.split("到");
				climate = strs[1];
			}
		}
		if (mWeatherBg.containsKey(climate)) {
			bgRes = mWeatherBg.get(climate);
		}
		return bgRes;
	}

	public Weatherinfo getmCurWeatherinfo() {
		return mCurWeatherinfo;
	}

	public SimpleWeatherinfo getCurSimpleWeatherinfo() {
		return mCurSimpleWeatherinfo;
	}

	public SimpleCity getCurSimpleCity() {
		return this.mCurSimpleCity;
	}

	public void setCurSimpleCity(SimpleCity sc) {
		this.mCurSimpleCity = sc;
		// 初始化当前的城市完成之后初始化当前城市播报音频
		try {
			Thread thread = new Thread() {
				@Override
				public void run() {
					WeatherHttpMethod whm = new WeatherHttpMethod(
							getApplicationContext());
					String path = whm.GetAudioPath(mSpUtil.getAuthCode(),
							mCurSimpleCity.cityCode);
					if (path != null && path != "") {
						Message m = new Message();
						m.what = AUDIO_PATH;
						m.obj = path;
						mHandler.sendMessage(m);
					}
				}
			};
			thread.start();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public String GetCurAudioPath() {
		return this.curAudioPath;
	}

	public void setCurAudioPath(String path) {
		this.curAudioPath = path;
	}

	public Map<String, SimpleCity> getSimpleCitys() {
		return this.allCitys;
	}

	public void setSimpleCitys(Map<String, SimpleCity> ac) {
		this.allCitys = ac;
	}

	public void setCurSimpleWeatherinfo(SimpleWeatherinfo simpleWeatherinfo) {
		this.mCurSimpleWeatherinfo = simpleWeatherinfo;
	}

	public void setmCurWeatherinfo(Weatherinfo mCurWeatherinfo) {
		this.mCurWeatherinfo = mCurWeatherinfo;
	}

	public Pm2d5 getmCurPm2d5() {
		return mCurPm2d5;
	}

	public void setmCurPm2d5(Pm2d5 mCurPm2d5) {
		this.mCurPm2d5 = mCurPm2d5;
	}

	private void initWeatherIconMap() {
		mWeatherIcon = new HashMap<String, Integer>();
		mWeatherIcon.put("暴雪", R.drawable.biz_plugin_weather_baoxue);
		mWeatherIcon.put("暴雨", R.drawable.biz_plugin_weather_baoyu);
		mWeatherIcon.put("大暴雨", R.drawable.biz_plugin_weather_dabaoyu);
		mWeatherIcon.put("大雪", R.drawable.biz_plugin_weather_daxue);
		mWeatherIcon.put("大雨", R.drawable.biz_plugin_weather_dayu);

		mWeatherIcon.put("多云", R.drawable.biz_plugin_weather_duoyun);
		mWeatherIcon.put("雷阵雨", R.drawable.biz_plugin_weather_leizhenyu);
		mWeatherIcon.put("雷阵雨冰雹",
				R.drawable.biz_plugin_weather_leizhenyubingbao);
		mWeatherIcon.put("晴", R.drawable.biz_plugin_weather_qing);
		mWeatherIcon.put("沙尘暴", R.drawable.biz_plugin_weather_shachenbao);

		mWeatherIcon.put("特大暴雨", R.drawable.biz_plugin_weather_tedabaoyu);
		mWeatherIcon.put("雾", R.drawable.biz_plugin_weather_wu);
		mWeatherIcon.put("小雪", R.drawable.biz_plugin_weather_xiaoxue);
		mWeatherIcon.put("小雨", R.drawable.biz_plugin_weather_xiaoyu);
		mWeatherIcon.put("阴", R.drawable.biz_plugin_weather_yin);

		mWeatherIcon.put("雨夹雪", R.drawable.biz_plugin_weather_yujiaxue);
		mWeatherIcon.put("阵雪", R.drawable.biz_plugin_weather_zhenxue);
		mWeatherIcon.put("阵雨", R.drawable.biz_plugin_weather_zhenyu);
		mWeatherIcon.put("中雪", R.drawable.biz_plugin_weather_zhongxue);
		mWeatherIcon.put("中雨", R.drawable.biz_plugin_weather_zhongyu);
	}

	private void initWarningIconMap() {
		mWarningIcon = new HashMap<String, Integer>();
		mWarningIcon.put("寒潮蓝色预警", R.drawable.hcblue);
		mWarningIcon.put("寒潮黄色预警", R.drawable.hcyellow);
		mWarningIcon.put("寒潮橙色预警", R.drawable.hcorange);
		mWarningIcon.put("寒潮红色预警", R.drawable.hcred);
		mWarningIcon.put("道路结冰黄色预警", R.drawable.dljbyellow);
		mWarningIcon.put("道路结冰橙色预警", R.drawable.dljborange);
		mWarningIcon.put("道路结冰红色预警", R.drawable.dljbred);
		mWarningIcon.put("霾黄色预警", R.drawable.myellow);
		mWarningIcon.put("霾橙色预警", R.drawable.morange);
		mWarningIcon.put("霾红色预警", R.drawable.mred);
		mWarningIcon.put("大雾黄色预警", R.drawable.dwyellow);
		mWarningIcon.put("大雾橙色预警", R.drawable.dworange);
		mWarningIcon.put("大雾红色预警", R.drawable.dwred);
		mWarningIcon.put("霜冻蓝色预警", R.drawable.sdblue);
		mWarningIcon.put("霜冻黄色预警", R.drawable.sdyellow);
		mWarningIcon.put("霜冻橙色预警", R.drawable.sdorange);
		mWarningIcon.put("冰雹橙色预警", R.drawable.bborange);
		mWarningIcon.put("冰雹红色预警", R.drawable.bbred);
		mWarningIcon.put("雷电黄色预警", R.drawable.ldyellow);
		mWarningIcon.put("雷电橙色预警", R.drawable.ldorange);
		mWarningIcon.put("雷电红色预警", R.drawable.ldred);
		mWarningIcon.put("干旱橙色预警", R.drawable.ghorange);
		mWarningIcon.put("干旱红色预警", R.drawable.ghred);
		mWarningIcon.put("高温黄色预警", R.drawable.gwyellow);
		mWarningIcon.put("高温橙色预警", R.drawable.gworange);
		mWarningIcon.put("高温红色预警", R.drawable.gwred);
		mWarningIcon.put("沙尘暴黄色预警", R.drawable.scbyellow);
		mWarningIcon.put("沙尘暴橙色预警", R.drawable.scborange);
		mWarningIcon.put("沙尘暴红色预警", R.drawable.scbred);
		mWarningIcon.put("大风蓝色预警", R.drawable.dfblue);
		mWarningIcon.put("大风黄色预警", R.drawable.dfyellow);
		mWarningIcon.put("大风橙色预警", R.drawable.dforange);
		mWarningIcon.put("大风红色预警", R.drawable.dfred);
		mWarningIcon.put("暴雪蓝色预警", R.drawable.bxblue);
		mWarningIcon.put("暴雪黄色预警", R.drawable.bxyellow);
		mWarningIcon.put("暴雪橙色预警", R.drawable.bxorange);
		mWarningIcon.put("暴雪红色预警", R.drawable.bxred);
		mWarningIcon.put("暴雨蓝色预警", R.drawable.byblue);
		mWarningIcon.put("暴雨黄色预警", R.drawable.byyellow);
		mWarningIcon.put("暴雨橙色预警", R.drawable.byorange);
		mWarningIcon.put("暴雨红色预警", R.drawable.byred);
		mWarningIcon.put("台风蓝色预警", R.drawable.tfblue);
		mWarningIcon.put("台风黄色预警", R.drawable.tfyellow);
		mWarningIcon.put("台风橙色预警", R.drawable.tforange);
		mWarningIcon.put("台风红色预警", R.drawable.tfred);

	}

	private void initWidgetWeather() {
		mWidgetWeatherIcon = new HashMap<String, Integer>();
		mWidgetWeatherIcon.put("暴雪", R.drawable.w17);
		mWidgetWeatherIcon.put("暴雨", R.drawable.w10);
		mWidgetWeatherIcon.put("大暴雨", R.drawable.w10);
		mWidgetWeatherIcon.put("大雪", R.drawable.w16);
		mWidgetWeatherIcon.put("大雨", R.drawable.w9);

		mWidgetWeatherIcon.put("多云", R.drawable.w1);
		mWidgetWeatherIcon.put("雷阵雨", R.drawable.w4);
		mWidgetWeatherIcon.put("雷阵雨冰雹", R.drawable.w19);
		mWidgetWeatherIcon.put("晴", R.drawable.w0);
		mWidgetWeatherIcon.put("沙尘暴", R.drawable.w20);

		mWidgetWeatherIcon.put("特大暴雨", R.drawable.w10);
		mWidgetWeatherIcon.put("雾", R.drawable.w18);
		mWidgetWeatherIcon.put("小雪", R.drawable.w14);
		mWidgetWeatherIcon.put("小雨", R.drawable.w7);
		mWidgetWeatherIcon.put("阴", R.drawable.w2);

		mWidgetWeatherIcon.put("雨夹雪", R.drawable.w6);
		mWidgetWeatherIcon.put("阵雪", R.drawable.w13);
		mWidgetWeatherIcon.put("阵雨", R.drawable.w3);
		mWidgetWeatherIcon.put("中雪", R.drawable.w15);
		mWidgetWeatherIcon.put("中雨", R.drawable.w8);
	}

	/**
	 * 初始化应用背景
	 * */
	private void initApplicationBackground() {
		mWeatherBg = new HashMap<String, Integer>();
		mWeatherBg.put("雪", R.drawable.snow);
		mWeatherBg.put("大雪", R.drawable.snow);
		mWeatherBg.put("小雪", R.drawable.snow);
		mWeatherBg.put("雨", R.drawable.rain);
		mWeatherBg.put("小雨", R.drawable.rain);
		mWeatherBg.put("暴雨", R.drawable.rain);
		mWeatherBg.put("大雨", R.drawable.rain);
		mWeatherBg.put("阵雨", R.drawable.rain);
		mWeatherBg.put("中雨", R.drawable.rain);
		mWeatherBg.put("晴", R.drawable.sun);
		mWeatherBg.put("多云", R.drawable.cloud);
		mWeatherBg.put("阴", R.drawable.nosun);
	}

	private void initCityList() {
		mCityList = new ArrayList<City>();
		mSections = new ArrayList<String>();
		mMap = new HashMap<String, List<City>>();
		mPositions = new ArrayList<Integer>();
		mIndexer = new HashMap<String, Integer>();
		mCityDB = openCityDB();// 这个必须最先复制完,所以我放在单线程中处理
		new Thread(new Runnable() {

			@Override
			public void run() {
				// TODO Auto-generated method stub
				isCityListComplite = false;
				prepareCityList();
				mHandler.sendEmptyMessage(CITY_LIST_SCUESS);
			}
		}).start();
	}

	private void initAllCitys() {
		allCitys = new HashMap<String, SimpleCity>();
		try {
			new Thread(new Runnable() {

				@Override
				public void run() {
					// TODO Auto-generated method stub
					StationHttpMethod shm = new StationHttpMethod(
							getApplicationContext());
					List<SimpleCity> cs = shm.GetSimpleCitys(mSpUtil
							.getAuthCode());
					Map<String, SimpleCity> temp = new HashMap<String, SimpleCity>();
					if (cs != null && cs.size() > 0) {
						for (int i = 0; i < cs.size(); i++) {
							temp.put(cs.get(i).cityCode, cs.get(i));
						}
					}
					Message m = new Message();
					m.what = ALL_CITYS;
					m.obj = temp;
					mHandler.sendMessage(m);
				}

			}).start();

		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	// 初始化当前城市
	private void initalCurSimpleCity() {
		try {
			if (this.allCitys != null) {
				SimpleCity s = this.allCitys.get(getResources().getString(
						R.string.yueyang_citycode));
				// this.mCurSimpleCity=s;
				this.setCurSimpleCity(s);
			}
			if (this.mCurSimpleCity == null
					|| this.mCurSimpleCity.cityCode == null
					|| this.mCurSimpleCity.cityCode == "") {
				SimpleCity s = new SimpleCity();
				s.cityCode = getResources()
						.getString(R.string.yueyang_citycode);
				s.cityName = getResources()
						.getString(R.string.yueyang_cityname);
				// this.mCurSimpleCity=s;
				this.setCurSimpleCity(s);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	private boolean prepareCityList() {
		mCityList = mCityDB.getAllCity();// 获取数据库中所有城市
		for (City city : mCityList) {
			String firstName = city.getFirstPY();// 第一个字拼音的第一个字母
			if (firstName.matches(FORMAT)) {
				if (mSections.contains(firstName)) {
					mMap.get(firstName).add(city);
				} else {
					mSections.add(firstName);
					List<City> list = new ArrayList<City>();
					list.add(city);
					mMap.put(firstName, list);
				}
			} else {
				if (mSections.contains("#")) {
					mMap.get("#").add(city);
				} else {
					mSections.add("#");
					List<City> list = new ArrayList<City>();
					list.add(city);
					mMap.put("#", list);
				}
			}
		}
		Collections.sort(mSections);// 按照字母重新排序
		int position = 0;
		for (int i = 0; i < mSections.size(); i++) {
			mIndexer.put(mSections.get(i), position);// 存入map中，key为首字母字符串，value为首字母在listview中位置
			mPositions.add(position);// 首字母在listview中位置，存入list中
			position += mMap.get(mSections.get(i)).size();// 计算下一个首字母在listview的位置
		}
		return true;
	}

	// 获取下级地市
	public Map<String, String> GetSubCitys(String location) {
		Map<String, String> result = new HashMap<String, String>();
		try {
			Bundle bundle = mCityDB.getSubLocations(location);
			String err_str = bundle.getString("error");
			if (err_str.equals("success") == true) {
				String temp = "";
				ArrayList<String> codes_list = bundle
						.getStringArrayList("codes_list");
				ArrayList<String> values_list = bundle
						.getStringArrayList("values_list");
				if (codes_list == null || values_list == null) {
					result.put("0000", "该城市没有地级市天气信息");
				}
				int size = codes_list.size();
				for (int i = 0; i < size; i++) {
					temp += codes_list.get(i) + "\t\t\t\t" + values_list.get(i)
							+ "\n";
					result.put(codes_list.get(i), values_list.get(i));
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return result;
	}

	BroadcastReceiver netChangeReceiver = new BroadcastReceiver() {

		@Override
		public void onReceive(Context context, Intent intent) {
			// TODO Auto-generated method stub
			if (intent.getAction().equals(NET_CHANGE_ACTION)) {
				if (mListeners.size() > 0)// 通知接口完成加载
					for (EventHandler handler : mListeners) {
						handler.onNetChange();
					}
			}
			mNetWorkState = NetUtil.getNetworkState(mApplication);
		}

	};

	public static abstract interface EventHandler {
		public abstract void onCityComplite();

		public abstract void onNetChange();
	}
}
